package com.shanghaionstar.user;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;

import com.onstar.cn.auth.userProfile.Vehicle;
import com.onstar.cn.common.exception.OnStarException;
import com.onstar.cn.common.util.Constants;
import com.onstar.cn.common.util.PreferencesUtls;
import com.onstar.cn.framework.annotation.FindViewById;
import com.onstar.cn.framework.mvp.base.core.BaseFragment;
import com.onstar.cn.framework.mvp.base.core.BaseFragmentActivity;
import com.onstar.cn.framework.utils.GsonHelper;
import com.onstar.cn.weight.ProgressLayout;
import com.shanghaionstar.OnstarApplication;
import com.shanghaionstar.R;
import com.shanghaionstar.activity.MoreActivity;
import com.shanghaionstar.alarm.AlarmActionType;
import com.shanghaionstar.alarm.AlarmProxy;
import com.shanghaionstar.enumtype.FunctionNameFindId;
import com.shanghaionstar.user.adapter.ChangeVehicleAdapter;
import com.shanghaionstar.user.bean.ReplenishEntity;
import com.shanghaionstar.user.bean.SwitchVehicleEntity;
import com.shanghaionstar.user.iview.IChangeVehicleView;
import com.shanghaionstar.user.iview.ReplenishViewImpl;
import com.shanghaionstar.user.presenter.ChangeVehiclePresenter;
import com.shanghaionstar.user.presenter.ReplenishPresenter;
import com.shanghaionstar.utils.AlertDialogUtil;
import com.shanghaionstar.utils.ApplicationUtil;
import com.shanghaionstar.utils.BusinessUtil;
import com.shanghaionstar.utils.FinalConfigParams;
import com.shanghaionstar.weight.CommonNoDatasLayout;
import com.shanghaionstar.weight.TopLayout;

import java.util.List;

/**
 * Created by 7828wc on 16/8/30.
 * 切换车辆界面
 */
public class ChangeVehicleFragment extends BaseFragment implements IChangeVehicleView {
    @FindViewById
    private TopLayout top_layout;
    @FindViewById
    private CommonNoDatasLayout no_datas_layout;
    @FindViewById
    private ListView vehicle_list;
    @FindViewById
    private ProgressLayout progress_layout;
    private ChangeVehiclePresenter presenter;

    private String firstName;
    private String lastName;

    private ReplenishPresenter replenishPresenter;

    public ReplenishPresenter getReplenishPresenter() {
        if (replenishPresenter == null) {
            replenishPresenter = new ReplenishPresenter(baseActivity.getScheduler());
            replenishPresenter.setView(new ReplenishViewImpl() {
                @Override
                public void needName(boolean need) {
                    setLoading(false);
                    if (need) {
                        BusinessUtil.sendReportByClickType(baseActivity, FunctionNameFindId.SwitchInfo3Vehicles_SubmitName.getStringValue());
                        Intent intent = new Intent(baseActivity, ReplenishInfo3Activity.class);
                        intent.putExtra("from", ChangeVehicleFragment.class.getSimpleName());
                        startActivityForResult(intent, Activity.RESULT_FIRST_USER);
                    } else {
                        switchVehicle(false);
                    }
                }

                @Override
                public void onFailed(Throwable throwable) {
                    super.onFailed(throwable);
                    setLoading(false);
                }
            });
        }
        return replenishPresenter;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Activity.RESULT_FIRST_USER && resultCode == ReplenishInfo3Activity.REPLENISH_SUCCESS) {
            if (data != null) {
                ReplenishEntity entity = (ReplenishEntity) (data.getSerializableExtra("replenishInfo"));
                if (entity != null) {
                    firstName = entity.getFirstName();
                    lastName = entity.getLastName();
                    switchVehicle(true);
                }
            }
        }
    }

    @Override
    public int getLayoutId() {
        return R.layout.more_change_vehicle;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        btnBackClick(top_layout);

        presenter = new ChangeVehiclePresenter(((MoreActivity) getActivity()).getScheduler());
        presenter.setView(this);
        presenter.start();
    }

    @Override
    public void switchVehicleSuccess() {
        OnstarApplication onstarApplication = (OnstarApplication) getActivity().getApplication();
        onstarApplication.setRes(null);
        //切换车辆成功后将爱车评估服务协议状态数据清除
//        onstarApplication.setCarAssessStatusItem(null);
        BaseFragmentActivity fragmentActivity = (BaseFragmentActivity) getActivity();
        if (fragmentActivity instanceof MoreActivity) {
            ((MoreActivity) fragmentActivity).setEngineNumber(null);
            ((MoreActivity) fragmentActivity).setPlateNumber(null);
        }
        //此时取消车检提醒闹钟（参车主生活车检功能）
        new AlarmProxy(onActivity()).cancel(AlarmActionType.VEHICLE_INSPECTION_ACTION);

        AlertDialogUtil.showAlertDialog(getActivity(), R.string.dialog_warning,
                R.string.option_save_account_success, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        PreferencesUtls.getInstance(getActivity()).putBoolean(FinalConfigParams.LOG_OUT, true);
//                        BusinessUtil.updateConfigValue(FinalConfigParams.LOG_OUT, FinalConfigParams.TRUE,
//                                getActivity());
//                        BusinessUtil.updateConfigValue(FinalConfigParams.UPDATE_BANNER, FinalConfigParams.TRUE,
//                                getActivity());
                        PreferencesUtls.getInstance(getActivity()).putBoolean(FinalConfigParams.UPDATE_BANNER, true);
                        BusinessUtil.updateConfigValue(FinalConfigParams.ISLOADDATAS, FinalConfigParams.TRUE,
                                getActivity());
                        BusinessUtil.refreshPolling(getActivity());
                        BusinessUtil.autoRefresh(getActivity());
                        if (ApplicationUtil.getInstance().isExpiredSubscriber()) {
                            getActivity().sendBroadcast(new Intent(Constants.BROADCAST_OVERDUE));
                        }
                        back();
                    }
                });
    }

    @Override
    public void setLoading(boolean isLoading) {
        progress_layout.setVisibility(isLoading ? View.VISIBLE : View.GONE);
    }

    @Override
    public void onResponseError(OnStarException e) {
        AlertDialogUtil.showDialogByOnstarException(getActivity(), e);
    }

    @Override
    public void onReponseSuccess(final List<Vehicle> object) {
        if (object != null && object.size() > 0) {
            ChangeVehicleAdapter adapter = new ChangeVehicleAdapter(object, onActivity());
            adapter.setSelectVin(ApplicationUtil.getInstance().getVin());
            vehicle_list.setAdapter(adapter);

            adapter.setOnItemClick(new ChangeVehicleAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(int arg0) {
                    Vehicle currentVehicle = ApplicationUtil.getInstance().getCurrentVehicle();
                    if (currentVehicle != null) {
                        if (object.get(arg0).getVin().equalsIgnoreCase(currentVehicle.getVin())) {
                            return;
                        } else {
                            switchVehicle = object.get(arg0);
                            validateNeedName(switchVehicle.getVin());
                        }
                    }
                }
            });

            vehicle_list.setVisibility(View.VISIBLE);
            no_datas_layout.setVisibility(View.GONE);
        } else {
            vehicle_list.setVisibility(View.GONE);
            no_datas_layout.setVisibility(View.VISIBLE);
        }
    }

    private void validateNeedName(String vin) {
        setLoading(true);
        getReplenishPresenter().validateNeedName(vin);
    }

    private Vehicle switchVehicle;

    private void switchVehicle(boolean needName) {
        if (switchVehicle != null)
            presenter.switchVehicle(switchVehicle.getAccountID(), switchVehicle, getBody(needName));
    }

    private String getBody(boolean needName) {
        SwitchVehicleEntity entity = new SwitchVehicleEntity();
        entity.setVin(switchVehicle.getVin());
        entity.setIdpUserID(ApplicationUtil.getInstance().getIdpID());
        entity.setNickName(ApplicationUtil.getInstance().getIdpID());
        if (needName) {
            entity.setFirstName(firstName);
            entity.setLastName(lastName);
        }
        entity.setSubscriberID(ApplicationUtil.getInstance().getSubscriberID());
        return GsonHelper.toJson(entity);
    }

    @Override
    public Activity onActivity() {
        return getActivity();
    }
}
